package com.ninong.ker.admin.service.impl;

import java.io.File;
import java.util.Arrays;
import java.util.List;

import com.google.common.collect.Lists;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.ninong.ker.admin.domain.Storage;
import com.ninong.ker.admin.mapper.StorageMapper;
import com.ninong.ker.admin.service.StorageService;
import com.ninong.ker.admin.service.dto.StorageDTO;
import com.ninong.ker.common.exception.CmdException;
import com.ninong.ker.common.tools.Constants;
import com.ninong.ker.common.tools.FileUtil;
import com.ninong.ker.common.tools.enums.BusinessEnum;

import cn.hutool.core.util.ObjectUtil;
 
/**
 * 
 * @author 鸠摩智
 * @date 2020年12月8日 上午10:21:39
 */
@Service
public class StorageServiceImpl extends ServiceImpl<StorageMapper, Storage>implements StorageService {
	
	@Value("${cmd.file.path}")
	private String serverPath;

	@Override
	public PageInfo<Storage> listPage(StorageDTO dto) {
		PageHelper.startPage(dto.getCurrentPage(), dto.getPageSize());
		QueryWrapper<Storage> query = new QueryWrapper<>();
		query.eq("deleted", Constants.DEFAULT_YES);
		if (!StringUtils.isEmpty(dto.getRealName())) {
			query.like("real_name", dto.getRealName());
		}
		List<Storage> storages = baseMapper.selectList(query);
		return new PageInfo<Storage>(storages);
	}

	@Override
	public List<Storage> create(MultipartFile[] files) {
		List<Storage> storages = Lists.newArrayList();
		for (MultipartFile multipartFile : files) {
			String suffix = FileUtil.getExtensionName(multipartFile.getOriginalFilename());
			String type = FileUtil.getFileType(suffix);
			String name = multipartFile.getOriginalFilename();
			String size = FileUtil.getSize(multipartFile.getSize());
			File file = FileUtil.upload(multipartFile, serverPath +File.separator+ type +  File.separator);
			if(ObjectUtil.isNull(file)){
				throw new CmdException(BusinessEnum.UPLOAD_FAILURE);
			}
			Storage  storage = new  Storage(name, suffix, type+File.separator+file.getName(), type, size);
			baseMapper.insert(storage);
			storages.add(storage);
		}
		return  storages;
	}


	@Override
	public void delete(String[] ids) {
		List<String> idList = Arrays.asList(ids);
		idList.forEach(id -> {		
			Storage entity = new Storage();
			entity.setId(id);
			entity.setDeleted(false);
			baseMapper.updateById(entity);
		});
		
	}

}
